/**
 * Created by De Niro on 15-4-21.
 */

app.config(['$httpProvider',function($httpProvider) {
    // Use x-www-form-urlencoded Content-Type
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

    /**
     * The workhorse; converts an object to x-www-form-urlencoded serialization.
     * @param {Object} obj
     * @return {String}
     */
    var param = function(obj) {
        var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

        for(name in obj) {
            value = obj[name];

            if(value instanceof Array) {
                for(i=0; i<value.length; ++i) {
                    subValue = value[i];
                    fullSubName = name + '[' + i + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            }
            else if(value instanceof Object) {
                for(subName in value) {
                    subValue = value[subName];
                    fullSubName = name + '[' + subName + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            }
            else if(value !== undefined && value !== null)
                query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
        }

        return query.length ? query.substr(0, query.length - 1) : query;
    };

    // Override $http service's default transformRequest
    $httpProvider.defaults.transformRequest = [function(data) {
        return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
    }];
}]);
app.directive('regPhone', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ctrl) {
            var regPhone = /^1[34578]{1}\d{9}$/;
            scope.$watch(attrs.ngModel, function() {
                if (regPhone.exec($(element).val()))
                    ctrl.$setValidity('regphone', true);
                else {
                    ctrl.$setValidity('regphone', false);
                }
            });
        }
    }
}).directive('regPsw', function() {
        return {
            require: 'ngModel',
            link: function(scope, element, attrs, ctrl) {;
                scope.$watch(attrs.ngModel, function() {
                    var charLength = $(element).val().length;
                    if (charLength>5 && charLength<19)
                        ctrl.$setValidity('regpsw', true);
                    else {
                        ctrl.$setValidity('regpsw', false);
                    }
                });
            }
        }
    }).directive('scrollToBottom',function(){
    return {
        restrict: 'A',
        link: function(scope,element,attr) {
            if (scope.$last === true) {
                    $("body").animate({scrollTop: $('body').height()});
            }
        }
    }
}).directive('blink', function () {
    return {
        restrict:'A',
        link:function(scope,element,attr){
            $(element).fadeIn(1500).fadeOut(1500);
        }
    }
}).directive('unCheckedMessage',function(hyContact){
    return {
        restrict:'A',
        link:function(scope, element, attrs, ctrl){
            scope.$watch('unChecked',function(newVal){
                if(!newVal){
                    for(var temp in hyContact.data){
                        if(hyContact.data.hasOwnProperty(temp)){
                            if(hyContact.data[temp]['unChecked']){
                                $(element).show();
                                return;
                            }
                        }
                    }
                    $(element).hide();
                }else{
                    $(element).show();
                }
            });
        }
    }
}).directive('ngThumb', ['$window', function($window) {
        var helper = {
            support: !!($window.FileReader && $window.CanvasRenderingContext2D),
            isFile: function(item) {
                return angular.isObject(item) && item instanceof $window.File;
            },
            isImage: function(file) {
                var type =  '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
                return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
            }
        };

        return {
            restrict: 'A',
            link: function(scope, element, attributes) {
                if (!helper.support) return;

                var params = scope.$eval(attributes.ngThumb);

                if (!helper.isImage(params.file)) return;

                var canvas = $('canvas');
                var reader = new FileReader();

                reader.onload = onLoadFile;
                reader.readAsDataURL(params.file);

                function onLoadFile(event) {
                    var img = new Image();
                    img.onload = onLoadImage;
                    img.src = event.target.result;
                }

                function onLoadImage() {
                    var width = params.width || this.width / this.height * params.height;
                    var height = params.height || this.height / this.width * params.width;
                    canvas.attr({ width: width, height: height });
                    canvas[0].getContext('2d').drawImage(this, 0, 0, width, height);
                }
            }
        };
    }]);;
app.controller('mainController',function($scope,$rootScope,$http,$location,hyUser,hyMessage,hyContact,hyPushStream){
    $scope.banner = {};
    $rootScope.invite = false;
    $scope.banner.content = '连接服务器中..';
    $scope.hyContact = '';
    hyContact.syncPromise('backEnd/contact.php').then(function(data){
        $scope.hyContact = hyContact.data;
        //同步完成 hyContact已更新 data即为hyContact.data
        //把在线状态的更新放在回调里面执行时因为两个请求都会对同一张表进行操作 容易出错
        $http.post('backEnd/refresh.php',{
            id:hyUser.id
        });
    });
    $scope.infoPeople = {};


    $scope.chat = function(id){
        if(!$scope.hyContact[id]['group']){
            $location.path('/chatting/'+id);
        }else{
            $location.path('/groupChatting/'+id);
        }
        $rootScope.invite = false;
    }
    var offLine = function(){
        //删除联系人中没有说过话的
        //使用jQuery是因为IE下的onbeforeunload需要发送异步请求,因此用jquery设置async: false之后发送
        $.ajax({url:'backEnd/logout.php',
            async: false,
            type : "post",
            dataType:'json',
            data:{
                id:hyUser.id,
                mode:'keep-session'
            }});
        hyContact.save();
        hyMessage.save();
        hyPushStream.onmessage = null;
        hyPushStream.sendMessage(JSON.stringify(['offline',hyUser.id]));
    }
    $(window).on("beforeunload",offLine);
    if (navigator.userAgent.indexOf("Safari") > -1) {
        $(window).on("pagehide",offLine);
    }

    hyPushStream.onmessage = manageMessage;//回调函数，收到消息的处理逻辑写在_manageEvent函数中
    hyPushStream.onstatuschange = onlineMessage;
    function onlineMessage(){
            if(hyPushStream.readyState == PushStream.OPEN){
                var messageTemp = ["online",hyUser.id,hyUser.nickName,hyUser.iconPath,hyUser.sex];
                hyPushStream.sendMessage(JSON.stringify( messageTemp ));
                $scope.banner.content = false ;
            }
            if(hyPushStream.readyState == PushStream.CLOSED){
                $scope.banner.content = '连接失败';
            }
    }
    function manageMessage( eventMessage ){
        $scope.$apply(function(){
            if( eventMessage != '' ){
                var message = $.parseJSON(eventMessage);
                if( message[0] == "message" ){
                    //Array("message", sender, receiver, content);
                    if(message[1] != hyUser.id){
                        if ((message[2] == hyUser.id)||($scope.hyContact[message[2]]&&$scope.hyContact[message[2]]['group'])){
//                           如果收信者为我 或者 收信者在联系人中且收信者为group
                            var temp = {
                                sender:message[1],
                                receiver:message[2],
                                content:message[3],
                                type:'message'
                            };
                            var timeTemp = new Date();
                                timeTemp = timeTemp.getTime();
                            temp['time'] = timeTemp;
                                hyMessage.push(temp);
                            if(message[2] == hyUser.id){
                                $scope.hyContact[message[1]]['everTalk'] = true;
                                $scope.hyContact[message[1]]['latestTalk'] = message[3];
                                $scope.hyContact[message[1]]['latestTime'] = timeTemp;
                                if($location.path() != '/chatting/'+message[1]){
                                    //这是防止正在与单人聊天 或者 群聊
                                    $scope.hyContact[message[1]]['unChecked'] = true;
                                    $scope.$broadcast('newMessage');
                                }
                            }else{
                                $scope.hyContact[message[2]]['latestTalk'] = message[3];
                                $scope.hyContact[message[2]]['latestTime'] = timeTemp;
                                if($location.path() != '/groupChatting/'+message[2] ){
                                    $scope.hyContact[message[2]]['unChecked'] = true;
                                    $scope.$broadcast('newMessage');
                                }
                            }
                        }
                    }
                }else if( message[0] == "offline" ){
                    $scope.hyContact[message[1]]['online'] = false;
                }else if(message[0] == "online"){
                    //["online",hyUser.id,hyUser.nickName,hyUser.iconPath,hyUser.sex]
                    if(message[1] != hyUser.id){
                        if(!$scope.hyContact[message[1]]){
                            $scope.hyContact[message[1]] = {everTalk:false,id:message[1]};
                        }
                        var tempContact = $scope.hyContact[message[1]];
                        tempContact['nickName'] = message[2];
                        tempContact['iconPath'] = message[3];
                        tempContact['sex'] = message[4];
                        tempContact['online'] = true;
                    }
                }else if(message[0]=="create"){
                    //message 结构为 Array("create",hyUser.id,peopleToInvite,groupName);
                    if(message[1]!=hyUser.id){
                        //如果'我'在成员之中
                        var index;
                        if((index = $.inArray(hyUser.id, message[2]))>-1){
                            //如果这个群聊是新的 而不是旧群聊加人
                            var tempTime = new Date(),
                                temp = {
                                    sender:message[1],
                                    receiver:message[3],
                                    //receiverNickName:inviteMessageNickname,
                                    type:'inviteMessage',
                                    time:tempTime.getTime()
                                },
                                tempNickName = "";
                            for(var i=0;i<message[2].length;i++){
                                tempNickName += (message[2][i]==hyUser.id)?(hyUser.nickName+' '):($scope.hyContact[message[2][i]].nickName+" ");
                            }
                            temp.receiverNickName = tempNickName;
                            hyMessage.push(temp);
                            var infoTemp = {};
                            infoTemp['nickName'] = $scope.hyContact[message[1]]['nickName']+" "+$scope.hyContact[message[2][(index==0)?1:0]]['nickName']+" 等";
                            infoTemp['everTalk'] = "true";
                            infoTemp['id'] = message[3];
                            message[2][index] = message[1];
                            infoTemp['member'] = message[2];
                            infoTemp['iconPath'] = "img/icon/1.jpg";
                            infoTemp['group'] = true;
                            infoTemp['latestTime'] = tempTime.getTime();
                            infoTemp['unChecked'] = true;
                            $scope.hyContact[message[3]] = infoTemp;
                        }
                    }
                }else if(message[0] == 'invite'){
                    //invite消息格式:
                    //['invite',hyUser.id,新加成员数组,groupName,老成员数组]
                    if(message[1]!=hyUser.id){
                        if($scope.hyContact[message[3]] || ($.inArray(hyUser.id,message[2])>-1)){
                            var i,index;
                            if($scope.hyContact[message[3]]){
                                for(i=$scope.hyContact[message[3]]['member'].length;i<message[2].length;i++){
                                    $scope.hyContact[message[3]]['member'].push(message[2][i]);
                                }
                            }else if((index = $.inArray(hyUser.id,message[2]))>-1){
                                var infoTemp = {};
                                infoTemp['nickName'] = $scope.hyContact[message[1]]['nickName']+" "+$scope.hyContact[message[4][0]]['nickName']+" 等";
                                infoTemp['everTalk'] = "true";
                                infoTemp['id'] = message[3];
                                message[2][index] = message[1];
                                infoTemp['member'] = message[2];
                                for(i = 0;i < message[4].length;i++ ){
                                    infoTemp['member'].push(message[4][i]);
                                }
                                infoTemp['iconPath'] = "img/icon/1.jpg";
                                infoTemp['group'] = true;
                                $scope.hyContact[message[3]]= infoTemp;
                            }
                            $scope.hyContact[message[3]]['latestTime'] = tempTime.getTime();
                            if($location.path() != '/groupChatting/'+message[2] ){
                                $scope.hyContact[message[2]]['unChecked'] = true;
                            }
                            var tempTime = new Date(),
                                temp = {
                                    sender:message[1],
                                    receiver:message[3],
                                    //receiverNickName:inviteMessageNickname,
                                    type:'inviteMessage',
                                    time:tempTime.getTime()
                                },
                                tempNickName = "";
                            for(i=0;i<message[2].length;i++){
                                tempNickName += (message[2][i]==hyUser.id)?(hyUser.nickName+' '):($scope.hyContact[message[2][i]].nickName+" ");
                            }
                            temp.receiverNickName = tempNickName;
                            hyMessage.push(temp);
                        }
                    }
                }else if(message[0] == 'anonyMessage'){
                    //['anonyMessage',hyUser.id,$scope.id,$scope.content,$scope.anonymousNickName];
                    if(message[1]!=hyUser.id){
                        if($scope.hyContact[message[2]]){
                            var temp = {
                                senderNickName:message[4],
                                receiver:message[2],
                                content:message[3],
                                type:'anonyMessage',
                                isMe:false
                                },
                                timeTemp = new Date();
                                timeTemp = timeTemp.getTime();
                                temp['time'] = timeTemp;
                            hyMessage.push(temp);
                            $scope.hyContact[message[2]]['latestTalk'] = message[3];
                            $scope.hyContact[message[2]]['latestTime'] = timeTemp;
                            if($location.path() != '/groupChatting/'+message[2] ){
                                $scope.hyContact[message[2]]['unChecked'] = true;
                                $scope.$broadcast('newMessage');
                            }
                        }
                    }
                }else if(message[0] == 'picMessage'){
                    //['picMessage',hyUser.id,$scope.id,response.data];
                    if(message[1] != hyUser.id){
                        if ((message[2] == hyUser.id)||($scope.hyContact[message[2]]&&$scope.hyContact[message[2]]['group'])){
//                           如果收信者为我 或者 收信者在联系人中且收信者为group
                            var temp = {
                                sender:message[1],
                                receiver:message[2],
                                picPath:message[3],
                                type:'picMessage'
                            };
                            var timeTemp = new Date();
                            timeTemp = timeTemp.getTime();
                            temp['time'] = timeTemp;
                            hyMessage.push(temp);
                            if(message[2] == hyUser.id){
                                $scope.hyContact[message[1]]['everTalk'] = true;
                                $scope.hyContact[message[1]]['latestTalk'] = "图片";
                                $scope.hyContact[message[1]]['latestTime'] = timeTemp;
                                if($location.path() != '/chatting/'+message[1]){
                                    //这是防止正在与单人聊天 或者 群聊
                                    $scope.hyContact[message[1]]['unChecked'] = true;
                                    $scope.$broadcast('newMessage');
                                }
                            }else{
                                $scope.hyContact[message[2]]['latestTalk'] = "图片";
                                $scope.hyContact[message[2]]['latestTime'] = timeTemp;
                                if($location.path() != '/groupChatting/'+message[2] ){
                                    $scope.hyContact[message[2]]['unChecked'] = true;
                                    $scope.$broadcast('newMessage');
                                }
                            }
                        }
                    }
                }else if(message[0] == 'anonyPicMessage'){
                    //['anonyPicMessage',hyUser.id,$scope.id,response.data,$scope.anonymousNickName];
                    if(message[1]!=hyUser.id){
                        if($scope.hyContact[message[2]]){
                            var temp = {
                                    senderNickName:message[4],
                                    receiver:message[2],
                                    picPath:message[3],
                                    type:'anonyPicMessage',
                                    isMe:false
                                },
                                timeTemp = new Date();
                            timeTemp = timeTemp.getTime();
                            temp['time'] = timeTemp;
                            hyMessage.push(temp);
                            $scope.hyContact[message[2]]['latestTalk'] = "图片";
                            $scope.hyContact[message[2]]['latestTime'] = timeTemp;
                            if($location.path() != '/groupChatting/'+message[2] ){
                                $scope.hyContact[message[2]]['unChecked'] = true;
                                $scope.$broadcast('newMessage');
                            }
                        }
                    }
                }
            }
        });
    }
    hyPushStream.connectToChannel('heyue');
    $scope.showPersonalInfo = function(id){
        console.log(id);
        $("#infoModal").modal('show');
        $scope.infoPeople.nickName = $scope.hyContact[id]['nickName'];
        $scope.infoPeople.iconPath = $scope.hyContact[id]['iconPath'];
        $http.post('backEnd/personalInfo.php', {
            user_id:id
        }).success(function(data) {
            console.log(data);
            if(data.info != "emptyInfo"){
                $scope.infoPeople.motto = data.data.motto;
                $scope.infoPeople.age = data.data.age;
                $scope.infoPeople.position = data.data.position;
                $scope.infoPeople.public = data.data.public;
            }else{
                $scope.infoPeople.motto = "";
                $scope.infoPeople.age = "";
                $scope.infoPeople.position = "";
                $scope.infoPeople.public = true;
            }
        });
    }
}).controller('chattingController',function($scope,$timeout,$location,$routeParams,$rootScope,FileUploader,hyMessage,hyUser,hyPushStream){
    var uploader = $scope.uploader = new FileUploader({
        url: 'backEnd/picUpload.php',
        queueLimit:1,
        autoUpload:true
    });
    uploader.filters.push({
        name: 'imageFilter',
        fn: function(item /*{File|FileLikeObject}*/, options) {
            var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
            return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
        }
    });
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
        if(response.success){
            console.log(response.data);
            //alert('图片上传成功');
            uploader.clearQueue();
            var tempMessage = ['picMessage',hyUser.id,$scope.id,response.data];
            hyPushStream.sendMessage(JSON.stringify(tempMessage));
            var tempTime = new Date(),
                tempObj = {
                    sender:hyUser.id,
                    receiver:$scope.id,
                    picPath:response.data,
                    type:'picMessage',
                    time:tempTime.getTime()
                };
            $scope.hyMessage.push(tempObj);
            $scope.hyContact[$scope.id]['latestTalk'] = "图片";
            var tempTime = new Date();
            tempTime = tempTime.getTime();
            $scope.hyContact[$scope.id]['latestTime'] = tempTime;
        }else{
            alert("图片上传失败");
            uploader.clearQueue();
        }
    };
    $scope.hyMessage = hyMessage;
    $scope.id = $routeParams.id;
    $scope.hyUser = hyUser ;
    $scope.content = "";
    $scope.inviteList  = {};
    if($scope.hyContact[$scope.id]&&$scope.hyContact[$scope.id]['unChecked']){
        $scope.hyContact[$scope.id]['unChecked'] = false;
    }
    $scope.respond = function(){
        if($scope.content == ""){
            return;
        }
        var tempMessage = ['message',hyUser.id,$scope.id,$scope.content];
        hyPushStream.sendMessage(JSON.stringify(tempMessage));
        var tempTime = new Date(),
            tempObj = {
                sender:hyUser.id,
                receiver:$scope.id,
                content:$scope.content,
                type:'message',
                time:tempTime.getTime()
            };
        $scope.hyMessage.push(tempObj);
        $scope.hyContact[$scope.id]['everTalk'] = true;
        $scope.hyContact[$scope.id]['latestTalk'] = $scope.content;
        var tempTime = new Date();
        tempTime = tempTime.getTime();
        $scope.hyContact[$scope.id]['latestTime'] = tempTime;
        $scope.content = "";
        $("#message-input").css('height','34px');
        $("#chatting-widget").css('margin-bottom','50px');
    }
    $scope.backward = function(){
        window.history.go(-1);
    }
    $scope.add = function(){
        $("#inviteModal").modal('show');
    }
    $("#message-input").each(function(){
        this.style.height=this.scrollHeight+'px';
    });
    $("#message-input").bind({
        input:function(){
            this.style.height=this.scrollHeight + 'px';
            $("#chatting-widget").css('margin-bottom',(16+this.scrollHeight)+'px');
        }
    });

    $scope.sendInvite = function(){
        $rootScope.invite = true;
        var temp,
            tempObj,
            tempTime = new Date(),
            tempArray = [$scope.id],
            inviteMessageNickname = ""+$scope.hyContact[$scope.id]['nickName']+" ",//这是用来显示 "您邀请xx yy zz 加入房间"
            tempGroupName = generateRandomString();
        for (temp in $scope.inviteList){
            if($scope.inviteList.hasOwnProperty(temp)){
                if($scope.inviteList[temp] === true){
                    tempArray.push(temp+'');
                    inviteMessageNickname+=($scope.hyContact[temp].nickName+" ");
                }
            }
        }
        temp = ['create',hyUser.id,tempArray,tempGroupName];
        $scope.hyContact[tempGroupName] = {id:tempGroupName,
            member:tempArray,
            everTalk:true,
            group:true,
            iconPath:"img/icon/1.jpg",
            latestTime:tempTime.getTime(),
            nickName:$scope.hyContact[tempArray[0]]['nickName']+' '+$scope.hyContact[tempArray[1]]['nickName']+' 等'}
        hyPushStream.sendMessage(JSON.stringify(temp));
        tempObj = {
            sender:hyUser.id,
            receiver:tempGroupName,
            receiverNickName:inviteMessageNickname,
            type:'inviteMessage',
            time:tempTime.getTime()
        };
        $scope.hyMessage.push(tempObj);

        $("#inviteModal").modal('hide');
        $timeout(function(){
            $location.path('/groupChatting/'+tempGroupName);
        },500);
    }

}).controller('chatController',function($scope,hyMessage){
    $scope.unChecked = false;
    $scope.$on("newMessage", function (event) {
        $scope.unChecked = true;
    });
    $scope.menu = 'chat';
}).controller('contactController',function($scope,hyMessage){
    $scope.unChecked = false;
    $scope.$on("newMessage", function (event) {
        $scope.unChecked = true;
    });
    $scope.menu = 'contact';
}).controller('configController',function($scope,$http,hyMessage,hyUser){
    $scope.menu = 'config';
    $scope.unChecked = false;
    $scope.$on("newMessage", function (event) {
        $scope.unChecked = true;
    });
    $scope.hyUser = hyUser;
    $scope.nickName = hyUser.nickName;
    $scope.motto = " ";
    $scope.age = " ";
    $scope.position = " ";
    $scope.public = "1";
    $scope.inputNickName = false;
    $scope.inputMotto = false;
    $scope.inputAge = false;
    $scope.inputPosition = false;
    $scope.inputPublic = false;
    $scope.transferPublic = function(public){
        if(public == "1"){
            return "是";
        }else{
            return "否";
        }
    }
    $scope.clearInput = function(event){
        $scope.inputNickName = $scope.inputMotto = $scope.inputAge = $scope.inputPosition = $scope.inputPublic = false;
    }
    $('body').on('click', function(event) {
        if ($(event.target).closest('.config-item').length == 0) {
            //没有点击
            if ($scope.inputNickName || $scope.inputMotto || $scope.inputAge || $scope.inputPosition || $scope.inputPublic) {
                $scope.clearInput();
            }
        }
        $scope.$apply();
    });
    $scope.submitNickName = function(){
        if($scope.nickName == ""){
            alert('昵称不能为空');
            $scope.nickName = hyUser.nickName;
            return;
        }
        $http.post('backEnd/editPersonalInfo.php', {
            changeItem:'nickName',
            newValue:$scope.nickName
        }).success(function(data) {
            hyUser.nickName = $scope.nickName;
        });
    }
    $scope.submitMotto = function(){
        $http.post('backEnd/editPersonalInfo.php', {
            changeItem:'motto',
            newValue:$scope.motto
        }).success(function(data) {
            //console.log(data);
        });
    }
    $scope.submitAge = function(){
        $http.post('backEnd/editPersonalInfo.php', {
            changeItem:'age',
            newValue:$scope.age
        }).success(function(data) {
            //console.log(data);
        });
    }
    $scope.submitPosition = function(){
        $http.post('backEnd/editPersonalInfo.php', {
            changeItem:'position',
            newValue:$scope.position
        }).success(function(data) {
            //console.log(data);
        });
    }
    $scope.submitPublic = function(){
        $http.post('backEnd/editPersonalInfo.php', {
            changeItem:'public',
            newValue:$scope.public
        }).success(function(data) {
            //console.log(data);
        });
    }
    $http.post('backEnd/personalInfo.php', {
        user_id:hyUser.id
    }).success(function(data) {
        //console.log(data);
        if(data.info != "emptyInfo"){
            $scope.motto = data.data.motto;
            $scope.age = data.data.age;
            $scope.position = data.data.position;
            $scope.public = data.data.public;
        }
    });
    $scope.exit = function(){
        $http.post('backEnd/logout.php').success(function(data) {
            alert("成功退出");
            window.location.href = "index.php";
        });
    }
}).controller('groupChattingController',function($scope,$routeParams,$rootScope,hyMessage,hyUser,FileUploader,hyPushStream){
    var uploader = $scope.uploader = new FileUploader({
        url: 'backEnd/picUpload.php',
        queueLimit:1,
        autoUpload:true
    });
    uploader.filters.push({
        name: 'imageFilter',
        fn: function(item /*{File|FileLikeObject}*/, options) {
            var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
            return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
        }
    });
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
        if(response.success){
            console.log(response.data);
            //alert('图片上传成功');
            uploader.clearQueue();
            if(!$scope.anonymousMode){
                var tempMessage = ['picMessage',hyUser.id,$scope.id,response.data];
                hyPushStream.sendMessage(JSON.stringify(tempMessage));
                var tempTime = new Date(),
                    tempObj = {
                        sender:hyUser.id,
                        receiver:$scope.id,
                        picPath:response.data,
                        type:'picMessage',
                        time:tempTime.getTime()
                    };
                $scope.hyMessage.push(tempObj);
            }else{
                var tempMessage = ['anonyPicMessage',hyUser.id,$scope.id,response.data,$scope.anonymousNickName];
                hyPushStream.sendMessage(JSON.stringify(tempMessage));
                var tempTime = new Date(),
                    tempObj = {
                        senderNickName:$scope.anonymousNickName,
                        receiver:$scope.id,
                        picPath:response.data,
                        type:'anonyPicMessage',
                        time:tempTime.getTime(),
                        isMe:true
                    };
                $scope.hyMessage.push(tempObj);
            }

            $scope.hyContact[$scope.id]['latestTalk'] = "图片";
            var tempTime = new Date();
            tempTime = tempTime.getTime();
            $scope.hyContact[$scope.id]['latestTime'] = tempTime;
        }else{
            alert("图片上传失败");
            uploader.clearQueue();
        }
    };
    $scope.anonymousMode = false;
    $scope.anonymousNickName = ""
    $scope.anonymousChattingStart = function(){
        $scope.anonymousMode = true;
        $scope.anonymousNickName = "匿名用户"+generateAnonymousName();
    }
    $scope.anonymousChattingStop = function(){
        $scope.anonymousMode = false;
        $scope.anonymousNickName = "";
    }

    $scope.hyMessage = hyMessage;
    $scope.id = $routeParams.id;
    $scope.content = "";
    $scope.inviteList  = {};
    $scope.hyUser = hyUser;

    if($scope.hyContact[$scope.id]&&$scope.hyContact[$scope.id]['unChecked']){
        $scope.hyContact[$scope.id]['unChecked'] = false;
    }
    $scope.respond = function(){
        if($scope.content == ""){
            return;
        }
        if(!$scope.anonymousMode){
            var tempMessage = ['message',hyUser.id,$scope.id,$scope.content];
            hyPushStream.sendMessage(JSON.stringify(tempMessage));
            var tempTime = new Date(),
                tempObj = {
                    sender:hyUser.id,
                    receiver:$scope.id,
                    content:$scope.content,
                    type:'message',
                    time:tempTime.getTime()
                };
            $scope.hyMessage.push(tempObj);
        }else{
            var tempMessage = ['anonyMessage',hyUser.id,$scope.id,$scope.content,$scope.anonymousNickName];
            hyPushStream.sendMessage(JSON.stringify(tempMessage));
            var tempTime = new Date(),
                tempObj = {
                    senderNickName:$scope.anonymousNickName,
                    receiver:$scope.id,
                    content:$scope.content,
                    type:'anonyMessage',
                    time:tempTime.getTime(),
                    isMe:true
                };
            $scope.hyMessage.push(tempObj);
        }

        $scope.hyContact[$scope.id]['latestTalk'] = $scope.content;
        var tempTime = new Date();
        tempTime = tempTime.getTime();
        $scope.hyContact[$scope.id]['latestTime'] = tempTime;
        $scope.content = "";
        $("#message-input").css('height','34px');
        $("#chatting-widget").css('margin-bottom','50px');
    }
    $scope.backward = function(){
        if($rootScope.invite){
            window.history.go(-2);
        }else{
            window.history.go(-1);
        }
    }
    $scope.add = function(){
        $("#inviteModal").modal('show');
        console.log($scope.hyContact[$scope.hyContact[$scope.id]['member'][0]]);
    }
    $("#message-input").each(function(){
        this.style.height=this.scrollHeight+'px';
    });
    $("#message-input").bind({
        input:function(){
            this.style.height=this.scrollHeight + 'px';
            $("#chatting-widget").css('margin-bottom',(16+this.scrollHeight)+'px');
        },
        propertychange:function(){
            this.style.height=this.scrollHeight + 'px';
            $("#chatting-widget").css('margin-bottom',(16+this.scrollHeight)+'px');
        }
    });
    $scope.checkInviteList = function(){
        var temp;
        for (temp in $scope.inviteList){
            if($scope.inviteList.hasOwnProperty(temp)){
                if($scope.inviteList[temp] === true){
                    return true;
                }
            }
        }
        return false;
    }
    $scope.sendInvite = function(){
        var temp,
            tempObj,
            tempTime = new Date(),
            tempArray = [],
            inviteMessageNickname = "";//这是用来显示 "您邀请xx yy zz 加入房间"
        for (temp in $scope.inviteList){
            if($scope.inviteList.hasOwnProperty(temp)){
                if($scope.inviteList[temp] === true){
                    tempArray.push(temp);
                }
            }
        }
        temp = ['invite',hyUser.id,tempArray,$scope.id,$scope.hyContact[$scope.id]['member']];
        hyPushStream.sendMessage(JSON.stringify(temp));
        for (temp in $scope.inviteList){
            if($scope.inviteList.hasOwnProperty(temp)){
                if($scope.inviteList[temp] === true){
                    $scope.hyContact[$scope.id]['member'].push(temp);
                    inviteMessageNickname += ($scope.hyContact[temp].nickName+" ");
                }
            }
        }
        $scope.hyContact[$scope.id]['latestTime'] = tempTime.getTime();
        tempObj = {
            sender:hyUser.id,
            receiver:$scope.id,
            receiverNickName:inviteMessageNickname,
            type:'inviteMessage',
            time:tempTime.getTime()
        };
        $scope.hyMessage.push(tempObj);
        $("#inviteModal").modal('hide');
    }
}).controller('configPortraitController',function($scope,FileUploader,hyUser,$location){
    var img = new Image();
    img.onload = onLoadImage;
    img.src = "assets/"+hyUser.iconPath;

    function onLoadImage() {
        var width = this.width / this.height * 150;
        var height = 150;
        $('canvas').attr({ width: width, height: height });
        $('canvas')[0].getContext('2d').drawImage(this, 0, 0, width, height);
    }
    var uploader = $scope.uploader = new FileUploader({
        url: 'backEnd/portraitUpload.php',
        queueLimit:1
    });
    // FILTERS

    uploader.filters.push({
        name: 'imageFilter',
        fn: function(item /*{File|FileLikeObject}*/, options) {
            var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
            return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
        }
    });
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
        if(response.success){
            hyUser.iconPath = response.data;
            alert('头像修改成功');
            $location.path('/config');
        }else{
            alert("头像上传失败");
            $location.path('/config-portrait');
        }
    };
    $scope.backward = function(){
        window.history.go(-1);
    }
    $scope.remove = function(){
        if(!uploader.queue[0]){
            return;
        }
        uploader.clearQueue();
        var canvas = $('canvas');
        canvas[0].getContext('2d').clearRect(0,0,canvas[0].width,canvas[0].height);
        canvas.attr('height','150px').attr('width','150px');
    }
 }).controller('loginController',function($scope,$http){
    $scope.title = '登录';
    $scope.form = '';
    $scope.submit = function() {
        $scope.loginForm.$setValidity('validate', true);
        if ($scope.loginForm.$invalid) {
            return;
        }
        $http.post('backEnd/login.php',
            {
                phone:$scope.form.phone,
                password:hex_md5($scope.form.psw)
            }).success(function(data) {
                if(!data.success){
                    $scope.loginForm.$setValidity('validate', false);
                }else{
                    window.location.href = "chatroom.php";
                }
            });
    }
}).controller('registerController',function($scope,$http){
    $scope.title = '注册';
    $scope.submit = function() {
        $scope.regForm.$setValidity('validate', true);
        if ($scope.regForm.$invalid) {
            return;
        }
        console.log('post');
        $http.post('backEnd/register.php',
            {
                phone:$scope.form.phone,
                password:hex_md5($scope.form.psw),
                nickname:$scope.form.nickName,
                sex:$scope.form.sex
            }).success(function(data) {
                console.log(data);
                if(!data.success){
                    alert('此手机号码已被注册');
                }else{
                    window.location.href = "chatroom.php";
                }
            });
    }

});
function generateRandomString(){
    var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    var res = "";
    for(var i = 0; i < 10 ; i ++) {
        var id = Math.ceil(Math.random()*35);
        res += chars[id];
    }
    return res;
}
function generateAnonymousName(){
    var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    var res = "";
    for(var i = 0; i < 4 ; i ++) {
        var id = Math.ceil(Math.random()*35);
        res += chars[id];
    }
    return res;
}
